/*
 * 文件名：PostBusinessImpl.java
 * 版权：Copyright 2007-2015 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述： PostBusinessImpl.java
 * 修改人：yanshu
 * 修改时间：2015年12月24日
 * 修改内容：新增
 */
package com.feichuang.chineseWoodCarving.business.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.better517na.commons.Response;
import com.better517na.commons.StatusCode;
import com.better517na.javaKeyIdGenerator.DatabaseDefinition;
import com.better517na.javaKeyIdGenerator.TableDefinition;
import com.feichuang.chineseWoodCarving.business.IPostBusiness;
import com.feichuang.chineseWoodCarving.dao.ICommentaryDao;
import com.feichuang.chineseWoodCarving.dao.IPostDao;
import com.feichuang.chineseWoodCarving.dao.ImageDao;
import com.feichuang.chineseWoodCarving.model.MCommentary;
import com.feichuang.chineseWoodCarving.model.MImageVo;
import com.feichuang.chineseWoodCarving.model.MPagerRequestVo;
import com.feichuang.chineseWoodCarving.model.MPagerResultVo;
import com.feichuang.chineseWoodCarving.model.MPost;

/**
 * TODO 添加类的一句话简单描述.
 * <p>
 * TODO 详细描述
 * <p>
 * TODO 示例代码
 * 
 * <pre>
 * </pre>
 * 
 * @author yanshu
 */
@Service("postBusiness")
public class PostBusinessImpl extends BaseBusinessImpl implements IPostBusiness {

    /**
     * 供求信息/帖子持久化
     */
    @Resource(name = "postDao")
    private IPostDao postDao;

    /**
     * 评论信息持久化
     */
    @Resource(name = "commentaryDao")
    private ICommentaryDao commentaryDao;

    /**
     * 图片信息持久化
     */
    @Resource(name = "imageDao")
    private ImageDao imageDao;

    /**
     * {@inheritDoc}.
     */
    @Override
    public boolean insertPost(MPost post) {
        post.setKeyId(keyIDFactory.NewKeyID(DatabaseDefinition.GJJPKRFinancialStatementDB, TableDefinition.GJJPKRFinancialStatementDB_KcpRelationshipAccountYYYY));
        return postDao.insertPost(post);
    }

    /**
     * {动态查询}.
     */
    @Override
    public MPagerResultVo<MPost> selectPost(MPost post) {
        MPagerResultVo<MPost> res = new MPagerResultVo<MPost>();
        List<MPost> list = postDao.selectPost(post);
        if (list != null && list.size() > 0) {
            res.setDataInfo(list);
            res.setTotalCount(list.size());
        }
        return res;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public boolean deletePostByID(MPost post) {
        boolean result = postDao.deletePostByID(post);
        if (result) {
            // 删除帖子下面的评论和图片信息 可改为 异步删除 或通过数据库关系表主外键控制删除
            // 如果删除帖子成功,则帖子下面的评论一起删除
            MCommentary commentary = new MCommentary();
            // 绑定关系为commentary.PostId = post.keyIds
            commentary.setPostId(post.getKeyId());
            commentaryDao.deleteMCommentary(commentary);
            // 图片信息也该删除。后期加上
            // imageDao.d
        }
        return result;
    }

    /**
     * {@,此处略显蛋疼，懒得改了}.
     */
    @Override
    public MPagerResultVo<MPost> selectPostFuzzyQuer(MPost post, int currentpage, int size) {
        // TODO Auto-generated method stub
        MPagerResultVo<MPost> mpageRes = new MPagerResultVo<MPost>();
        List<MPost> postList = postDao.selectPostFuzzyQuer(post);
        if (postList != null && postList.size() > 0) {
            mpageRes.setTotalCount(postList.size());
            int begin = (currentpage - 1) * size;
            int end = size;
            if (size != 0) {
                end = begin + size - 1;
                if (end > postList.size()) {
                    end = postList.size() - 1;
                }
            }
            List<MPost> postListNew = new ArrayList<MPost>();
            for (int i = begin; i <= end; i++) {
                postListNew.add(postList.get(i));
            }
            // postListNew.addAll(postList.subList(begin, end));
            mpageRes.setDataInfo(postListNew);
        }
        return mpageRes;
    }

    /**
     * {@尼玛突然很想把MyBatis换成Hinernate啊，此处心情省略一万字}.
     */
    @Override
    public Response<MPost> selectPostByID(MPost post) {
        Response<MPost> res = new Response<MPost>();
        // 查询帖子基本信息
        MPost postRes = postDao.selectPostByID(post);
        // 查询帖子图片信息
        List<MImageVo> imagevoList = imageDao.selectImagesByBelongID(post.getKeyId());
        postRes.setImagevoList(imagevoList);
        MCommentary commentary = new MCommentary();
        commentary.setPostId(postRes.getKeyId());
        // 查询帖子评论
        List<MCommentary> commentaryList = commentaryDao.selectMCommentary(commentary);
        postRes.setCommentaryList(commentaryList);
        // 封装返回model
        res.setContent(post);
        res.setCode(StatusCode.SUCCESS);
        // 更新浏览次数， 如果查询速度慢后面可改为异步更新（待优化）
        updatePostViewNum(post);
        return res;
    }

    /**
     * TODO 更新浏览次数.
     * 
     * @param post
     */
    protected void updatePostViewNum(MPost post) {
        MPost postup = new MPost();
        postup.setKeyId(post.getKeyId());
        postup.setViewsNumber(post.getViewsNumber() + 1);
        postDao.updatePost(postup);
    }

    /**
     * {@分页查询}.
     */
    @Override
    public MPagerResultVo<MPost> selectPostForPage(MPagerRequestVo<MPost> pageRequest) {
        // 获取总数据量
        MPost postque = pageRequest.getDataModel();
        int count = postDao.selectPostCountForPage(pageRequest.getDataModel());
        // 计算分页起始和结束位置
        int begin = (pageRequest.getCurrentpage() - 1) * pageRequest.getSize();
        pageRequest.setBegin(begin);
        pageRequest.setEnd(pageRequest.getSize());
        // 获取具体信息
        List<MPost> list = postDao.selectPostForPage(pageRequest);
        if (postque.getPostType() == 2) {
            // 2用户发帖
            for (MPost post : list) {
                // String keyid = post.getKeyId();
                MCommentary commentary = new MCommentary();
                commentary.setPostId(post.getKeyId());
                List<MCommentary> commentaryList = commentaryDao.selectMCommentary(commentary);
                if (commentaryList != null) {
                    post.setReplayNumber(commentaryList.size());
                }
                post.setCommentaryList(commentaryList);
            }
        }
        // 组装结果
        MPagerResultVo<MPost> res = new MPagerResultVo<MPost>();
        res.setTotalCount(count);
        res.setDataInfo(list);
        // 返回信息
        return res;
    }
}
